#ifndef  _ICC_UDP_CLIENT_H_
#define  _ICC_UDP_CLIENT_H_

#include "poller.h"
#include <string>
using namespace std;

class UdpClient: public CPollerObject
{
public:
	UdpClient()
	{
		if ((netfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
		{
			log_boot("make udp socket error, err_msg[%s]", strerror(errno));
		}
		bzero(&m_RemoteAddr, sizeof (struct sockaddr_in));
	}
	virtual ~UdpClient(){};
public: //callback
	//virtual int Init(){return 0; }
	//virtual int InputNotify();

public: //method
	inline string GetSIp(){ return this->m_RemoteIp; }
	inline uint16_t GetPort() { return this->m_RemotePort; }

	int Connect(const char* ip, uint16_t port)
	{// just save addr
		strncpy(m_RemoteIp, ip, sizeof(m_RemoteIp)-1);
		m_RemotePort = port;

		bzero(&m_RemoteAddr, sizeof (struct sockaddr_in));
		m_RemoteAddr.sin_family = AF_INET;
		m_RemoteAddr.sin_port = htons(port);

		//m_RemoteAddr.sin_addr.s_addr = inet_addr(ip);
		if (inet_pton(AF_INET, ip, &m_RemoteAddr.sin_addr) <= 0)
		{
			log_boot("invalid address ip[%s], port[%d]", ip, port);
			return -1;
		}
		return 0;
	}

	int Connect(struct sockaddr_in& remote_addr)
	{
		m_RemotePort = remote_addr.sin_port;
		//m_RemoteIp = remote_addr.sin_addr.s_addr
		::bzero(&m_RemoteAddr, sizeof (struct sockaddr_in));
		::memcpy(&m_RemoteAddr, &remote_addr, sizeof(sockaddr_in));
		
		std::string ip = inet_ntoa(remote_addr.sin_addr);
		::bzero(m_RemoteIp, sizeof(m_RemoteIp));
		strncpy(m_RemoteIp, ip.c_str(), sizeof(m_RemoteIp)-1);
		m_RemotePort = ntohs(remote_addr.sin_port));
		return 0;
	}

	int Send(const char * raw_buff, int data_len)
	{
		// TODO: send pkg by loop buff
		int ret = ::sendto(netfd, raw_buff, data_len, 0, (struct sockaddr*)&m_RemoteAddr, sizeof(m_RemoteAddr));
		return ret;
	}
public:
	char	m_RemoteIp[128];
	uint16_t m_RemotePort;
	struct sockaddr_in m_RemoteAddr;
};
#endif

